<?php

if(!defined('AF')):

define('AF', TRUE);

define('START_TIME', microtime(TRUE));

define('AF_SEP', DIRECTORY_SEPARATOR);
define('AF_ROOT', dirname(__FILE__) . AF_SEP);
define('AF_MODULES_DIR', AF_ROOT . 'modules' . AF_SEP);
define('AF_INTERFACES_DIR', AF_ROOT . 'interfaces' . AF_SEP);
define('AF_BASE_DIR', AF_ROOT . 'base' . AF_SEP);
define('AF_FUNCTIONS_DIR', AF_ROOT . 'functions' . AF_SEP);
define('AF_PREFIX', 'AF');
define('AF_CLASS_EXT', '.class.php');

include_once AF_FUNCTIONS_DIR . 'AFFunctions.class.php';

// Include all interfaces
//AFFunctions::walk(AF_INTERFACES_DIR, function($interface){
//	include_once $interface; //MODDIR . $module . SEP);
//}, TRUE);

// Include all base classes
AFFunctions::walk(AF_BASE_DIR, function($class){
//	FN::import($class); //MODDIR . $module . SEP);
	include_once $class;
}, TRUE);

// Define all module fastcall handles
AFFunctions::walk(AF_MODULES_DIR, function($module){
	define(strtoupper($module), $module); //MODDIR . $module . SEP);
});

$debugger = new AFDebugger();
//$debugger->

function AF($module = NULL)
{
	return AFCore::getInstance($module);
}

class AFModuleImportException extends AFException {};

class AFCore extends AFClass
{
	private static $__instances = NULL;

	public function getClassName()
	{
		return 'AFCore';
	}

	public static function getInstance($module)
	{
		if(!isset(self::$__instances[$module]))
		{
			if($module == NULL)	// Create AFCore
			{
				self::$__instances[$module] = new AFCore();
			}
			else	// Create whatever requested
			{
				$path = AF_MODULES_DIR . $module . AF_SEP . AF_PREFIX . $module . 'Module' . AF_CLASS_EXT;
				if(!is_file($path))
				{
					throw new AFModuleImportException("Module $module not found ($path).", 1);
				}
				include_once $path;
				$moduleClassName = AF_PREFIX . $module . 'Module';
				if(!class_exists($moduleClassName))
				{
					throw new AFModuleImportException("Module $module has no class $moduleClassName declared.", 1);
				}
				if(!in_array('AFModule', class_parents($moduleClassName)))
				{
					throw new AFModuleImportException("Class $module/$moduleClassName must extend AFModule.", 1);
				}
				self::$__instances[$module] = new $moduleClassName();
			}
		}

		return self::$__instances[$module];
	}

	private function __construct()
	{
	}

	private $path = '/';
	private $userDir = '.';

	public function setPath($path)
	{
		$this->path = $path;
	}

	public function getPath()
	{
		return $this->path;
	}

	public function time($round = NULL)
	{
		return ($round === NULL)
			? microtime(TRUE) - START_TIME
			: round(microtime(TRUE) - START_TIME, 5);
	}

	public function userInit($dir)
	{
		$this->userDir = trim($dir, AF_SEP);
		if(is_dir($this->userDir))
		{
			FN::walk(array(
				$this->userDir . AF_SEP . 'models',
				$this->userDir . AF_SEP . 'controllers'
			), function($file){
				if(FN::checkExt($file, '.class.php'))
				{
					include_once $file;
				}
			}, TRUE);
		}
	}
};

endif;

?>
